package com.ling.module1sbbyyds.config.handler;

import com.ling.sbbyyds.entity.exception.ApiErrorInfoException;
import com.ling.sbbyyds.entity.exception.ApiWarningInfoException;
import com.ling.sbbyyds.interaction.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.annotation.Priority;
import javax.validation.ValidationException;


/**
 * 系统异常处理器
 * @author ling
 */

@Slf4j
@Priority(0)
@RestControllerAdvice(value = "com.ling")
public class SystemExceptionHandler {

    /**
     * 端口绑定异常
     * 一般出现在网络连接时出现
     * @param e 异常实体
     * @return 反馈
     */
    @ExceptionHandler(BindException.class)
    public ResultVo methodArgumentNotValidExceptionHandler(BindException e) {
        // 从异常对象中拿到ObjectError对象
        log.error("系统异常：",e);
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return ResultVo.fail(505, objectError.getDefaultMessage());
    }


    /**
     * 参数无效异常
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo handlerArgumentNotValidException(MethodArgumentNotValidException exception) {
        return ResultVo.fail(1001, exception.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * ValidationException 参数校验异常处理
     */
    @ExceptionHandler(ValidationException.class)
    public ResultVo handleValidationException(ValidationException e) {
        return ResultVo.fail(1001, e.getMessage());
    }

    /**
     * 系统错误异常处理,返回错误信息到客户端
     */
    @ExceptionHandler(ApiErrorInfoException.class)
    public ResultVo handleApiErrorInfoException(ApiErrorInfoException e) {
        return ResultVo.fail(555, e.getMessage());
    }

    /**
     * 系统警告异常处理,返回警告信息到客户端
     */
    @ExceptionHandler(ApiWarningInfoException.class)
    public ResultVo handleApiWarningInfoException(ApiWarningInfoException e) {
        return ResultVo.fail(600, e.getMessage());
    }

    /**
     * 捕获程序全局异常
     */
    @ExceptionHandler(Exception.class)
    public ResultVo handleException(Exception e) {
        log.error("系统内部异常:",e);
        return ResultVo.fail(505, "系统内部异常故障,也许是服务器着火了");
    }

}
